<template>
	<view>
		<view class="header">
			<view class="header-item" style="display: flex; justify-content: center; align-items: center;"
				@tap="onShowFamily">
				<view
					style="display:inline-block;max-width: 60vw; overflow: hidden; text-overflow:ellipsis; white-space: nowrap;font-weight: 800;font-size: 18px">
					{{ currentGroupName }}</view>
				<uni-icons custom-prefix="iconfont" type="icon-xiazhijiantou-copy" size="12"
					style="margin-left: 12rpx;transform: rotate(180deg);"
					:style="{transform:show?'rotate(0deg)':'rotate(180deg)'}"></uni-icons>
			</view>
			<view class="header-item u-f-ac" v-if="isShowRight">
				<uni-icons v-if="false" type="headphones" size="26" @tap="onBindtapMessage" style="margin-left:20rpx;"></uni-icons>
				<uni-icons v-if="false" type="chat" size="26" @click="onBindtapNotify" style="margin-left:20rpx;"></uni-icons>

				<uni-icons data-code="601000" data-eventName="start_add_dev" custom-prefix="iconfont" type="icon-jiahao" size="25" @tap="onBindtapAddDevice"
					style="margin-left:20rpx;" v-if="navigate === 'device'"></uni-icons>
				<!-- <view class="u-f-ajc">
					<image src="https://statics.xmcsrv.net/weixin/addSceneIcon.png" @tap="onBindtapAddScene" style="margin-left:20rpx;width: 45rpx;height: 45rpx;" v-if="navigate === 'scene'"></image>
				</view> -->
				<uni-icons custom-prefix="iconfont" type="icon-jiahao" size="25" @tap="onBindtapAddScene"
					style="margin-left:20rpx;" v-if="navigate === 'scene'"></uni-icons>
			</view>
		</view>

		<uni-popup ref="popup" type="top" @change="change" @maskClick="maskClick">
			<!-- #ifdef H5 -->
			<view class="popup-container-h5">
				<!-- #endif -->
				<!-- #ifndef H5 -->
				<view class="popup-container">
					<!-- #endif -->
					<j-cell-group :title="$t('General.home.myHome')" max-height="calc(20vh - 0rpx)">
						<template v-for="(item, index) in groupList">
							<j-cell v-if="item.isCreator" :key="item.id" :cellTitleWitch="'80vw'"
								:title="item.groupName" :more="false" @jftap="onBindtapFamily(item)">
								<view slot="tips">
									<uni-icons custom-prefix="iconfont" type="icon-duihao" size="24" color="#FF0025"
										style="margin-right:20rpx;" v-if="item.id === currentGroupId"></uni-icons>
								</view>
							</j-cell>
						</template>
					</j-cell-group>
					<j-cell-group :title="$t('General.family.joinedHome')" max-height="calc(50vh - 0rpx)">
						<scroll-view :scroll-y="true" style="max-height:20vh">
							<template v-for="(item, index) in groupList">
								<j-cell class="" v-if="!item.isCreator" :key="item.id" :cellTitleWitch="'80vw'"
									:title="item.familyName" :more="false" @jftap="onBindtapFamily(item)">
									<view slot="tips">
										<uni-icons custom-prefix="iconfont" type="icon-duihao" size="24" color="#FF0025"
											style="margin-right:20rpx;" v-if="item.id === currentGroupId"></uni-icons>
									</view>
								</j-cell>
							</template>
						</scroll-view>
					</j-cell-group>
					<j-cell :title="$t('General.family.homeManagement')" :more="false" @jftap="onBindtapFamilyManagement">
						<view slot="tips">
							<uni-icons custom-prefix="iconfont" type="icon-settings" size="24"
								style="margin-right:20rpx;"></uni-icons>
						</view>
					</j-cell>
				</view>
		</uni-popup>
	</view>
</template>

<script>
	const {
		splitArray
	} = require('@/utils/util.js');
	export default {
		data() {
			return {
				show: false,
				// 用户组列表
				groupList: [],
				// 当前用户组ID
				currentGroupId: '',
				// 当前用户组名称
				currentGroupName: '',
				isJoin: true,
                sns: [],
			};
		},
		props: {
            // 所有设备列表
            allDeviceList: {
                type: Array,
                default: []
            },
			// 指示组件在哪一个tab导航中展示
			navigate: {
				type: String,
				default: ''
			},
			isShowRight: {
				type: Boolean,
				default: true
			},
            deviceList: {
                type: Array,
                default: []
            },
			shareDeviceList:{
				type: Array,
				default: []
			}
		},
		watch: {
			groupList: {
				handler: function(res) {
					// 缓存
					uni.setStorageSync('groupList', res);
					// 循环对比缓存与集合，找到并将名称赋值
					// 如果未找到，则使用集合的第一个元素，并且缓存
					let currentGroupId = uni.getStorageSync('currentGroupId')
					let bool = false
					let joinList = []
					if (res.length > 0) {
						for (let i = 0; i < res.length; i++) {
							const item = res[i];
							if (item.id === currentGroupId) {
								bool = true
								if (item.isCreator) {
									this.currentGroupName = item.groupName
								} else {
									this.currentGroupName = item.familyName
								}
								break;
							}
							// if(!item.isCreator){
							// 	joinList.push(item)
							// }
							// console.log('其他家庭组：-----',joinList);
							// if(joinList.length >0){
							// 	this.isJoin = true
							// }else{
							// 	this.isJoin = false
							// }
						}
						if (!bool) {
							this.currentGroupId = res[0].id
							this.currentGroupName = res[0].groupName
							uni.setStorageSync('currentGroupId', res[0].id);
							uni.setStorageSync('currentGroupName', res[0].groupName);
						}
					}
				},
				deep: true
			},
			currentGroupId: {
				handler: function(res) {
					// 循环对比当前用户组与集合，找到并将名称赋值、缓存和触发事件
					for (let i = 0; i < this.groupList.length; i++) {
						const item = this.groupList[i];
						if (item.id === res) {
							if(item.isCreator){
								this.currentGroupName = item.groupName
							}else{
								this.currentGroupName = item.familyName
							}
							uni.setStorageSync('currentGroupId', res);
							uni.setStorageSync('currentGroupName', item.groupName);
							this.$emit('loadhandler', {
								currentGroupId: res
							});
							break
						}
					}
				},
				deep: true
			}
		},
		beforeCreate: function() {
			// console.log('===header:beforeCreate:');
		},
		created: function() {
			// console.log('===header:created:');
		},
		beforeMount: function() {
			// 在组件实例进入页面节点树时执行
			if (uni.getStorageSync('accessToken')) {
				this.getUserGroupListByPage();
			}
		},
		mounted: function() {
			// console.log('===header:mounted:');
			uni.$on('userGroupDel',this.RefreshUserGroupList);
		},
		beforeUpdate: function() {
			// console.log('===header:beforeUpdate:');
		},
		updated: function() {
			// console.log('===header:updated:');
		},
		beforeDestroy: function() {
			// console.log('===header:beforeDestroy:');
		},
		destroyed: function() {
			console.log('===header:destroyed:');
			uni.$off('userGroupDel',this.RefreshUserGroupList);
		},

		onPageShow: function() {
			// console.log('===header:onPageShow:');
			this.getCurrentGroup()
            // console.log("重新订阅家庭信息", this.sns);
            this.subscribeMqttInfo(this.sns)
		},

		onPageHide: function() {
			// console.log('===header:onPageHide:');
		},

		onPageResize: function() {
			// console.log('===header:onPageResize:');
		},

		/**
		 * 组件的方法列表
		 */
		methods: {
			RefreshUserGroupList(){
				this.getUserGroupListByPage()
			},
			// 获取当前家庭组（没有的时候选择第一个家庭组）
			getCurrentGroup() {
				this.groupList = uni.getStorageSync('groupList')
				this.currentGroupId = uni.getStorageSync('currentGroupId')
			},

			// 查询用户组列表
			getUserGroupListByPage() {
				getApp().globalData.api.getUserGroupListByPage({
					page: 1,
					limit: 999
				}, (result) => {
					let sns = [];
					this.groupList = result.data || [];
					this.groupList.forEach(item => {
						sns.push(item.id)
						if (item.creatorName) {
							item.familyName = item.creatorName.slice(0, 10) + '的家庭' + '(' + item
								.groupName + ')'
						} else {
							item.familyName = item.groupName
						}
					})
					// console.log(this.groupList)
                    this.sns = sns
					this.subscribeMqttInfo(sns)
				});
			},
			//mqtt订阅发送消息
			subscribeMqttInfo(sns) {
				let topic = [];
				sns.forEach((item) => {
					topic.push(`/group/${item}`)
				})
				// console.log(topic,'需要订阅的家庭数据')
				let arr = splitArray(topic, 20)
				if (arr.length > 0) {
					arr.forEach((item) => {
						getApp().globalData.mqtt.subscribe(item)
					})
				}
				// getApp().globalData.mqtt.subscribe(topic)
			},
			// 弹出层
			onShowFamily(ev) {
				if (this.show) {
					this.$refs.popup.close()
				} else {
					this.$refs.popup.open()
				}
			},

			// 选择某个家庭组
			onBindtapFamily(ev) {
				// console.log(ev,'家庭')
				this.currentGroupId = ev.id;
				this.$refs.popup.close();
				uni.setStorageSync('currentGroupName', ev.groupName);
				// 触发父页面函数
				// this.$emit('loadhandler',{
				// 	currentGroupId: this.currentGroupId
				// });
			},
			// 选择家庭管理
			onBindtapFamilyManagement(ev) {
				// console.log('家庭管理：', ev);
				this.$refs.popup.close()
				uni.navigateTo({
					url: '/jvss/pagesDevice/group/group-list/group-list'
				});
			},

			// 消息列表 TODO
			onBindtapMessage(ev) {
				// console.log('消息列表：');
				uni.navigateTo({
					url: '/jvss/pagesMine/help/help'
				});
			},

			// 通知列表 TODO
			onBindtapNotify(ev) {
				console.log('通知列表：', ev);
                if(!this.allDeviceList.length&&this.shareDeviceList.length==0) {
                    uni.showToast({
                        title: '未查到设备列表或设备列表为空',
                        icon: 'none'
                    })
                    return
                }
                let deviceList=[], obj
                this.deviceList.forEach(item => {
                    deviceList.push(item.deviceNo)
                })
                console.log(deviceList)
                if(this.deviceList.length>0) {
                    deviceList = JSON.stringify(deviceList)
                }
				uni.navigateTo({
					url: '/jvss/pagesDevice/device/device-live/door-lock/cloudMsg?type=2&deviceList='+deviceList
					// url:'/jvss/pagesDevice/device/device-live/door-lock/message?type=2'
					// url:'/jvss/pagesMine/msgPush/msgSubscribeDetail'

				})
			},

			// 添加设备（扫描） TODO
			onBindtapAddDevice(ev) {
				// console.log('添加设备（扫描）:', ev);

				uni.$emit('stopBlue')
				uni.navigateTo({
					url: '/jvss/pagesDevice/device/device-add/device-add'
				});
			},

			// 添加场景
			onBindtapAddScene(ev) {
				// console.log('添加场景：', ev);
				uni.navigateTo({
					url: '/jvss/pagesScene/scene-create/scene-create'
				});
			},

			change(ev) {
				// console.log('change:', ev);
				this.show = ev.show
			},

			maskClick(ev) {
				// console.log('maskClick:', ev);
				this.isShowFamily = false
			}
		}
	};
</script>
<style lang="scss" scoped>
	.header {
		// position: fixed;
		top: 0;
		/*  #ifdef  H5  */
		top: 80rpx;
		/* #endif */
		left: 0;
		z-index: 99;
		width: calc(100vw - 40rpx);
		height: 80rpx;
		line-height: 80rpx;
		padding: 0 20rpx;
		display: flex;
		justify-content: space-between;
		background: #f5f7fb;
	}

	.icon-xs {
		width: 22rpx;
		height: 22rpx;
		margin: 0 6rpx;
	}

	.icon-sm {
		width: 42rpx;
		height: 42rpx;
		margin: 0 6rpx;
	}

	.popup-container {
		background: #F5F7FB;
		padding-top: 80rpx;
	}

	.popup-container-h5 {
		background: #F5F7FB;
	}

	.popup-item {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		border-bottom: 1px solid #eeeeee;
		padding: 20rpx;
	}

	.popup-item:hover {
		background: #eeeeee;
	}

	.popup-item:last-child {
		border: none;
	}
</style>
